#include "qlogdatabaseview.h"

#include "styledbar.h"
#include "qbaseitemdelegate.h"
#include "qactiontoolbar.h"
#include "qdeviceinformationdialog.h"

#include "../shared/sqlite/qsqlitecontrol.h"

#include <QVBoxLayout>
#include <QHeaderView>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>

QLogDatabaseView::QLogDatabaseView(QWidget *parent) :
    QWidget(parent),
    m_styled_bar(new StyledBar),
    m_tree_widget(new QTreeWidget)
{
    QVBoxLayout* v=new QVBoxLayout;
    v->setMargin(0);
    v->setSpacing(0);

    v->addWidget(m_styled_bar);
    v->addWidget(m_tree_widget);

    setLayout(v);

    m_tree_widget->setFrameStyle(QFrame::NoFrame);
    m_tree_widget->setItemDelegate(new QBaseItemDelegate);
    m_tree_widget->header()->setMovable(false);
    m_tree_widget->setRootIsDecorated(false);
    m_tree_widget->setAlternatingRowColors(true);
    m_tree_widget->setHeaderLabels(QStringList()<<tr("No.")<<tr("Time")<<tr("User")
                                   <<tr("Tag")<<tr("Message"));
    setProperty("panelwidget",true);
}

void QLogDatabaseView::set_tool_bar(QList<QAction *> list)
{
    QActionToolBar *tool=new QActionToolBar;

    QList<QAction *> l=list;

    QAction* ac;

    ac=new QAction(this);
    ac->setIcon(QIcon(":/images/save.png"));
    ac->setText(tr("Save"));
    connect(ac,SIGNAL(triggered()),this,SLOT(save()));
    connect(this,SIGNAL(save_enabled(bool)),ac,SLOT(setEnabled(bool)));
    ac->setEnabled(false);
    l.append(ac);

    ac=new QAction(this);
    ac->setIcon(QIcon(":/images/clear.png"));
    ac->setText(tr("Clear"));
    connect(ac,SIGNAL(triggered()),this,SLOT(clear()));
    l.append(ac);

    ac=new QAction(this);
    ac->setSeparator(true);
    l.append(ac);

    ac=new QAction(this);
    ac->setText(tr("First"));
    ac->setIcon(QIcon(":/images/first.png"));
    connect(this,SIGNAL(first_enabled(bool)),ac,SLOT(setEnabled(bool)));
    connect(ac,SIGNAL(triggered()),this,SLOT(first()));
    ac->setEnabled(false);
    l.append(ac);

    ac=new QAction(this);
    ac->setText(tr("Previous"));
    ac->setIcon(QIcon(":/images/previous.png"));
    connect(this,SIGNAL(prev_enabled(bool)),ac,SLOT(setEnabled(bool)));
    connect(ac,SIGNAL(triggered()),this,SLOT(prev()));
    ac->setEnabled(false);
    l.append(ac);

    ac=new QAction(this);
    ac->setText(tr("Next"));
    ac->setIcon(QIcon(":/images/next.png"));
    connect(this,SIGNAL(next_enabled(bool)),ac,SLOT(setEnabled(bool)));
    connect(ac,SIGNAL(triggered()),this,SLOT(next()));
    ac->setEnabled(false);
    l.append(ac);

    ac=new QAction(this);
    ac->setText(tr("Last"));
    ac->setIcon(QIcon(":/images/last.png"));
    connect(this,SIGNAL(last_enabled(bool)),ac,SLOT(setEnabled(bool)));
    connect(ac,SIGNAL(triggered()),this,SLOT(last()));
    ac->setEnabled(false);
    l.append(ac);

    ac=new QAction(this);
    ac->setSeparator(true);
    l.append(ac);

    ac=new QAction(this);
    ac->setText(tr("Information"));
    ac->setIcon(QIcon(":/images/info.png"));
    connect(this,SIGNAL(save_enabled(bool)),ac,SLOT(setEnabled(bool)));
    connect(ac,SIGNAL(triggered()),this,SLOT(info()));
    ac->setEnabled(false);
    l.append(ac);

    ac=new QAction(this);
    ac->setSeparator(true);
    l.append(ac);


    tool->addButtonActions(l);

    QVBoxLayout *v=new QVBoxLayout;
    v->setMargin(0);
    v->setSpacing(0);
    v->addWidget(tool);

    m_styled_bar->setLayout(v);

    m_tree_widget->setColumnWidth(0,40);
    m_tree_widget->setColumnWidth(1,150);
    m_tree_widget->setColumnWidth(2,100);
    m_tree_widget->setColumnWidth(3,200);
}

void QLogDatabaseView::first()
{
    show_page(0);
}

void QLogDatabaseView::prev()
{
    if(m_current_index>0)
    {
        show_page(m_current_index-1);
    }
}

void QLogDatabaseView::next()
{
    if(m_current_index<((m_size-1)/MAX_SHOW))
    {
        show_page(m_current_index+1);
    }
}

void QLogDatabaseView::last()
{
    if(m_current_index<((m_size-1)/MAX_SHOW))
    {
        show_page((m_size-1)/MAX_SHOW);
    }
}

void QLogDatabaseView::clear()
{
    m_tree_widget->clear();
    m_current_index=0;
    m_size=0;
    m_path="";
    emit save_enabled(false);
    emit first_enabled(false);
    emit prev_enabled(false);
    emit next_enabled(false);
    emit last_enabled(false);
}

bool QLogDatabaseView::load(const QString &path)
{
    QSqliteControl sqlite;
    if(!sqlite.open(path))
    {
        return false;
    }

    m_query=sqlite.exec("select * from Log");
    m_system_query=sqlite.exec("select * from property");

    m_size=0;
    while(m_query.next())
    {
        m_size++;
    }
    show_page(0);
    m_path=path;
    emit save_enabled(true);
    return true;
}

void QLogDatabaseView::show_page(int index)
{
    int pt=index*MAX_SHOW;

    if(pt>=m_size)
    {
        return;
    }
    m_current_index=index;
    m_query.seek(pt);
    m_tree_widget->clear();
    int end=(m_size-pt)>MAX_SHOW?MAX_SHOW:(m_size-pt);

    for(int i=0;i<end;i++)
    {
        QTreeWidgetItem* item=new QTreeWidgetItem(m_tree_widget);
        item->setText(0,QString::number(i+pt+1));
        for(int j=0;j<4;j++)
        {
            item->setText(1+j,m_query.value(j).toString());
            item->setToolTip(1+j,m_query.value(j).toString());
        }
    }

    emit first_enabled(pt>0);
    emit prev_enabled(pt>0);
    emit next_enabled((pt+end)<m_size);
    emit last_enabled((pt+end)<m_size);
}

void QLogDatabaseView::save()
{
    QString str=QFileDialog::getSaveFileName(this,tr("Save"),QDir::currentPath(),
                                             tr("DB File(*.db)"));
    if(str!="" && str!=m_path)
    {
        QFile f(str);
        if(!f.open(QFile::ReadWrite))
        {
            QMessageBox::critical(this,tr("Warning"),tr("Save Failed!"));
            return;
        }
        QFile ff(m_path);
        if(!ff.open(QFile::ReadOnly))
        {
            QMessageBox::critical(this,tr("Warning"),tr("Save Failed!"));
            return;
        }
        f.resize(0);
        f.write(ff.readAll());
        f.close();
        ff.close();
    }
}

void QLogDatabaseView::info()
{
    QDeviceInformationDialog dlg(this);

    m_system_query.first();

    do
    {
        dlg.set_property(m_system_query.value(0).toString(),m_system_query.value(1).toString());
    }while(m_system_query.next());

    dlg.exec();
}
